//
//  SXWYDetailImageViewController.m
//  ShiXun
//
//  Created by lanou on 15/10/29.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXWYDetailImageViewController.h"
#import "SXRequestManager.h"
#import "SXWYDetailPhotoModel.h"
#import "SXWYDetailPhotoView.h"
#import "UIImageView+WebCache.h"
#import "UMSocial.h"
#import "MJPhoto.h"
#import "MJPhotoBrowser.h"
@interface SXWYDetailImageViewController ()<UIScrollViewDelegate>
@property(nonatomic, strong) UIScrollView *imageScrollView;
@property(nonatomic, strong) NSMutableArray *imageArray;
@property(nonatomic, strong) SXWYDetailPhotoView *photoView;
@property(nonatomic, copy) NSString *shareStr;
@end

@implementation SXWYDetailImageViewController

- (SXWYDetailPhotoView *)photoView
{
    if (_photoView == nil) {
        _photoView = [[SXWYDetailPhotoView alloc] initWithFrame:self.view.bounds];
        _photoView.imageScrollView.contentSize = CGSizeMake(_imageArray.count * kScreenWidth, kScreenHeight - 104);
        _photoView.imageScrollView.delegate = self;
        for (int i = 0; i < _imageArray.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] init];
            [imageView sd_setImageWithURL:[NSURL URLWithString:((SXWYDetailPhotoModel *)_imageArray[i]).imgurl] placeholderImage:[UIImage imageNamed:@"SX-placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                if (image.size.width != 0) {
                    CGFloat imageHeight =kScreenWidth * image.size.height / image.size.width;
                    imageView.frame = CGRectMake(kScreenWidth * i, (kScreenHeight - 130 - imageHeight) / 2, kScreenWidth, imageHeight);
                }
            }];
            imageView.userInteractionEnabled = YES;
            imageView.tag = i + 2000;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doTapImg:)];
            [imageView addGestureRecognizer:tap];
            [_photoView.imageScrollView addSubview:imageView];
        }
        _photoView.contentLabel.text = ((SXWYDetailPhotoModel *)_imageArray[0]).note;
        _photoView.contentScrollView.contentSize = CGSizeMake(kScreenWidth - 20, [SXWYDetailPhotoView heightOfString:_photoView.contentLabel.text]);
        _photoView.contentLabel.frame = CGRectMake(0, 0, kScreenWidth - 20, [SXWYDetailPhotoView heightOfString:_photoView.contentLabel.text]);
        _photoView.countLabel.text = [NSString stringWithFormat:@"1/%ld",_imageArray.count];
    }
    return _photoView;
}
- (void)doTapImg:(UITapGestureRecognizer *)tap
{
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:_imageArray.count];
    for (int i = 0; i<_imageArray.count; i++) {
        // 替换为中等尺寸图片
        NSString *url = [[_imageArray[i] imgurl] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:url]; // 图片路径
        photo.srcImageView = (UIImageView*)[self.view viewWithTag:i + 2000]; // 来源于哪个UIImageView
        [photos addObject:photo];
    }
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = tap.view.tag - 2000; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x / kScreenWidth;
    _photoView.contentLabel.text = ((SXWYDetailPhotoModel *)_imageArray[index]).note;
    _photoView.contentScrollView.contentSize = CGSizeMake(kScreenWidth - 20, [SXWYDetailPhotoView heightOfString:_photoView.contentLabel.text]);
    _photoView.contentLabel.frame = CGRectMake(0, 0, kScreenWidth - 20, [SXWYDetailPhotoView heightOfString:_photoView.contentLabel.text]);
    _photoView.countLabel.text = [NSString stringWithFormat:@"%ld/%ld", index + 1, _imageArray.count];
}
- (NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _imageArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIImageView *backgroundImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SXphotoBack"]];
    backgroundImg.frame = CGRectMake(0, 20, kScreenWidth, kScreenHeight);
    [self.view addSubview:backgroundImg];
    self.navigationController.navigationBar.hidden = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setNavigationBar];
    [self requestData];
    // Do any additional setup after loading the view.
}

- (void)requestData
{
    _photoStr = [_photoStr stringByReplacingOccurrencesOfString:@"|" withString:@"/"];
    NSString *URLStr = [kWYNewsDetailImageURLString stringByAppendingString:[NSString stringWithFormat:@"%@.json", _photoStr]];
    [SXRequestManager requestWithType:GET urlString:URLStr parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        for (NSDictionary *photoDic in dic[@"photos"]){
            SXWYDetailPhotoModel *model = [[SXWYDetailPhotoModel alloc] init];
            [model setValuesForKeysWithDictionary:photoDic];
            if (model.note.length == 0) {
                model.note = model.imgtitle;
            }
            [self.imageArray addObject:model];
        }
        _shareStr = dic[@"url"];
        [self.view addSubview:self.photoView];
         self.photoView.titleLabel.text = dic[@"setname"];
    } error:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}
// 设置返回和分享按钮
- (void)setNavigationBar
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"SX-yuedufanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(didClickLeft)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"SX-yuedushare"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(didClickRight)];
}
- (void)didClickLeft
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didClickRight
{
    [UMSocialConfig setFinishToastIsHidden:NO position:(UMSocialiToastPositionCenter)];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5632c41ce0f55a17390010c1"
                                      shareText:[NSString stringWithFormat:@"//分享图集 %@ %@", self.photoView.titleLabel.text, _shareStr]
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToInstagram, UMShareToSms,nil]
                                       delegate:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
